/* eslint-disable no-case-declarations */
/* eslint-disable eqeqeq */
/**
 * request 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request
 */
import { message } from 'antd';
import { extend } from 'umi-request';
import { history } from 'umi';

const errorHandler = (error) => {
  const { response } = error;
  return response ? response : {};
};
/**
 * 配置request请求时的默认参数
 */
const request = extend({
  prefix: REACT_APP_URL, //前缀代理  tasks.nangaoyun.com
  errorHandler,
  // 默认错误处理
  credentials: 'include', // 默认请求是否带上cookie
});
// request拦截器, 改变url 或 options.
request.interceptors.request.use(async (url, options) => {
  let token = localStorage.getItem('TOKENSTRING');
  if (token) {
    const headers =
      options.type == 'form'
        ? {
            Authorization: 'Bearer ' + token,
          }
        : {
            'Content-Type': 'application/json',
            Authorization: 'Bearer ' + token,
          };
    return {
      url: url,
      options: { ...options, headers: headers },
    };
  }
});

// response拦截器, 处理response
request.interceptors.response.use(async (response, options) => {
  if (options.responseType == 'blob') {
    const data = await response.clone().blob();
    let blobUrl = window.URL.createObjectURL(data);
    const a = document.createElement('a');
    a.style.display = 'none';
    let temp = response.headers.get('Content-Disposition').split(';')[1].split('=')[1] || '';
    let fileDefaultName = decodeURI(temp);
    let pathname = '表格';
    a.download = fileDefaultName || pathname + '.xls';
    a.href = blobUrl;
    a.click();
    a.remove();
  }
  const data = await response.clone().json();
  let returnThings = response;
  // 详情返回的response处理
  if (data?.code !== '0000') {
    switch (data.code) {
      case '1401':
        const res = await fetch(REACT_APP_URL + '/basics/auth/refreshToken', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            refreshToken: localStorage.getItem('REFRESHTOKEN'),
          }),
        });
        const responseData = await res.json();
        if (responseData.code === '0400') {
          history.push("/login")
        } else if (responseData.code === '0000') {
          const access_token = responseData?.data?.access_token;
          const refresh_token = responseData?.data?.refresh_token;
          localStorage.setItem('TOKENSTRING', access_token);
          localStorage.setItem('REFRESHTOKEN', refresh_token);
          returnThings = await request(options.url, {
            ...options,
          });
        }
        break;
      case '0401':
        history.push("/login")
        break;

      default:
        message.error(data?.msg);

        break;
    }
  }
  return returnThings;
});

export default request;
